package com.danskin.wechat.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.danskin.wechat.cache.JedisClient;
import com.danskin.wechat.dao.RelRolePrivilegeDao;
import com.danskin.wechat.dao.RoleInfoDao;
import com.danskin.wechat.dao.UserInfoDao;
import com.danskin.wechat.dao.WxMediaPlatformDao;
import com.danskin.wechat.entity.RelRolePrivilege;
import com.danskin.wechat.entity.RoleInfo;
import com.danskin.wechat.entity.UserInfo;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.entity.example.RoleInfoExample;
import com.danskin.wechat.entity.example.RoleInfoExample.Criteria;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.service.UserService;
import com.danskin.wechat.util.CookieUtils;
import com.danskin.wechat.util.JsonUtils;
import com.danskin.wechat.util.Page;
/**
 * User实体类对应的业务操作类接口
 * @author hanwei
 * @version [版本号:1.0]
 */
@Service
public class UserServiceImpl extends BaseServiceImpl implements UserService
{

	@Autowired
	private UserInfoDao userDao;
	
	@Autowired
	private WxMediaPlatformDao mpDao;
	
	@Autowired
	private JedisClient jedis;
	
	@Autowired
	private RoleInfoDao roleDao;
	
	@Autowired
	private RelRolePrivilegeDao relRolePrivilegeDao;
	
	

	@Value("${REDIS_USER_SESSION_KEY}")
	public String REDIS_USER_SESSION_KEY;
	@Value("${SSO_SESSION_EXPIRE}")
	public Integer SSO_SESSION_EXPIRE;


	


	@Override
	public List<UserInfo> getAllUser(Page page) {
		List<UserInfo> list = userDao.listPageGetAllUser(page);
		return list;
	}

	@Override
	public int updateUserByPrimaryKeySelective(Map<String, Object> map) {
		int updateUserByPrimaryKeySelective = userDao.updateUserByPrimaryKeySelective(map);
		List<Map<String,Object>> list = userDao.queryRelUserRoleByUserId(map);
		if(list.size()>0){
			userDao.updateRelUserRoleByUserId(map);
		}else{
			userDao.insertRelRoleUser(map);
		}
		add("修改用户信息", "账户模块");
		return updateUserByPrimaryKeySelective;
	}
	
	@Override
	public int updatePasswordByPrimaryKeySelective(Map<String, Object> map) {
		int i = userDao.updateUserByPrimaryKeySelective(map);
		add("修改密码", "账户模块");
		return i;
	}
	
	
	/**
	 * 可选列   插入
	 */
	@Override
	public int insertSelective(UserInfo user) {
		user.setUserPwd(DigestUtils.md5DigestAsHex(user.getUserPwd().getBytes()));
		int insertSelective = userDao.insertSelective(user);
		Map<String,Object> map=new HashMap<String, Object>();
		if(user.getRoleCode()>0){
			map.put("id", user.getId());
			map.put("roleCode", user.getRoleCode());
			map.put("createUser",user.getRoleName());
			map.put("createdTime", user.getCreatedTime());
			userDao.insertRelRoleUser(map);
		}
		add("增加用户", "账户模块");
		return insertSelective;
	}
	/**
	 * 根据条件获取用户列表
	 */
	@Override
	public List<UserInfo> getUserListByCondtion(Page page) {
		List<UserInfo> listPageGetUserByCondtion = userDao.listPageGetUserByCondtion(page);
		return listPageGetUserByCondtion;
	}
	/**
	 * 根据用户Id删除用户
	 */
	@Override
	public int deleteUserById(int id) {
		int i = userDao.deleteUserById(id);
		userDao.deleteRelUserRoleByUserId(id);
		add("删除账户", "账户模块");
		return i;
	}
	/**
	 * 根据id查询用户
	 */
	public UserInfo getUserByID(int userID){
		UserInfo user=userDao.queryByPrimaryKey(userID);
		if(0==user.getMpId()){
			user.setNickName("超级管理员");
		}else{
			WxMediaPlatform wxMediaPlatform = mpDao.selectByPrimaryKey(user.getMpId());
			user.setNickName(wxMediaPlatform.getNickName());
		}
		return user;
	}
	/**
	 * 根据用户名查询用户
	 */
	@Override
	public List<UserInfo>  queryByUserName(String userName) {
		  List<UserInfo> list = userDao.queryByUserName(userName);
		return list;
	}

	@Override
	public UserInfo getUserByToken(String token) {
		AccessResponse<Object> access = new AccessResponse<Object>();
		String string = jedis.get(REDIS_USER_SESSION_KEY+":"+token);
		jedis.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
		if (StringUtils.isBlank(string)) {
			access.setErrorCode("1");
			access.setErrorMsg("此session已经过期，请重新登录");
			return null;
		}
		UserInfo toPojo = JsonUtils.jsonToPojo(string, UserInfo.class);
		return toPojo;
	}
	
	@Override
	public AccessResponse userLogin(String username, String password, HttpServletRequest request,
			HttpServletResponse response) {
		AccessResponse<Object> access = new AccessResponse<Object>();
		List<UserInfo> list = this.queryByUserName(username);
		//如果没有此用户名
		if (null == list || list.size() == 0) {
			access.setErrorCode("1");
			access.setErrorMsg("用户名或密码错误");
			return access;
		}
		UserInfo user = list.get(0);
		//比对密码
		if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getUserPwd())) {
			access.setErrorCode("1");
			access.setErrorMsg("用户名或密码错误");
			return access;
		}
		//生成token
		String token = UUID.randomUUID().toString();
		//保存用户之前，把用户对象中的密码清空。
		user.setUserPwd(null);
		//把用户信息写入redis
		jedis.set(REDIS_USER_SESSION_KEY + ":" + token, JsonUtils.objectToJson(user));
		//设置session的过期时间
		jedis.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
		
		//添加写cookie逻辑 cookie的有效期是关闭浏览器失效
		//CookieUtils.setCookie(request, response, "SESSION_TOKEN", token);
		CookieUtils.saveCookie(request, response, "SESSION_TOKEN", token);
		//返回token
		access.setErrorCode("0");
		access.setErrorMsg("登陆成功");
		access.setData(token);
		return access;

	}

	@Override
	public List<RoleInfo> queryByRoleName(String roleName) {
		List<RoleInfo> list = userDao.queryByRoleName(roleName);
		return list;
	}

	@Override
	public int insertRoleAndMenu(RoleInfo role, List<String> list) {
		int i = roleDao.insertSelective(role);
		List<RelRolePrivilege> maueList=new ArrayList<RelRolePrivilege>();
		int j=0;
		if(i>0){
			Integer id=role.getId();
			role.setRoleCode(String.valueOf(id));
			roleDao.updateByPrimaryKeySelective(role);
			if(list.size()>0){
				for (String string : list) {
					RelRolePrivilege rolePrivilege=new RelRolePrivilege();
					rolePrivilege.setMenuCode(string);
					rolePrivilege.setRoleCode(String.valueOf(id));
					rolePrivilege.setCreateUser(role.getCreateUser());
					rolePrivilege.setCreatedTime(new Date());
					maueList.add(rolePrivilege);
				}
			}
			j = relRolePrivilegeDao.insertBatchSelective(maueList);
		}
		return j;
	}

	@Override
	public List<RoleInfo> getAllRoleInfoByMpId(Integer mpId) {
		RoleInfoExample example=new RoleInfoExample();
		Criteria criteria = example.createCriteria();
		criteria.andMpIdEqualTo(mpId);
		List<RoleInfo> list = roleDao.selectByExample(example);
		return list;
	}

	/**
	 * 销售端 登录专用
	 */
	@Override
	public AccessResponse userLogin(String username, String password) {
		AccessResponse<Object> access = new AccessResponse<Object>();
		List<UserInfo> list = this.queryByUserName(username);
		//如果没有此用户名
		if (null == list || list.size() == 0) {
			access.setErrorCode("400");
			access.setErrorMsg("用户名或密码错误");
			return access;
		}
		UserInfo user = list.get(0);
		//比对密码
		if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getUserPwd())) {
			access.setErrorCode("400");
			access.setErrorMsg("用户名或密码错误");
			return access;
		}
		//生成token
		String token = UUID.randomUUID().toString();
		Map<String,String> param=new HashMap<String, String>();
		param.put("token", token);
		param.put("userName", user.getUserName());
		int i = userDao.updateUserInfoTokenByUserName(param);
		
		access.setErrorCode("200");
		access.setErrorMsg("登陆成功");
		access.setData(token);
		return access;
	}
	/**
	 * 销售端专用
	 */
	@Override
	public UserInfo getUserByInfoToken(String token) {
		UserInfo queryUserInfoByToken = userDao.queryUserInfoByToken(token);
		return queryUserInfoByToken;
	}
	


	
	


	
}
